import re
from rest_framework import serializers

from users.models import User


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'username', 'mobile', 'email','password')
        extra_kwargs ={
            'password':{
                'max_length':20,
                'min_length':5,
                'write_only':True
            },
            'username':{
                'max_length':20,
                'min_length':8
            }
        }
    def validate_mobile (self, value):
        if not re.match('1[3-9]\d{9}',value):
            return serializers.ValidationError('不匹配')
        return value
    # 父类重写,密码加密
    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return  user